import Toast from 'tdesign-miniprogram/toast/index';
import {
  baseUrl,
  prefixUrl
} from '../../../config/api';
import {
  userType
} from '../../../config/constan';

Page({
  data: {
    // 个人信息数组
    personInfo: {
      avatarUrl: '',
      username: '点击获取',
      gender: 0,
      mobile: '',
      type: 0
    },
    //是否显示解绑确认框
    showUnbindConfirm: false,
    // 性别选择数组
    pickerOptions: [{
        name: '未设置',
        code: '0',
      }, {
        name: '男',
        code: '1',
      },
      {
        name: '女',
        code: '2',
      },
    ],
    picker2Options: userType,
    //控制弹出层的显示和隐藏，选择性别
    typeVisible: false,
    type2Visible: false
  },
  onShow() {
    let user = wx.getStorageSync("userInfo")
    if (user === '' || user === undefined) {
      wx.showToast({
        title: '未登录，无信息',
        icon: "error",
        duration: 2000,
        success() {
          setTimeout(function () {
            wx.navigateBack()
          }, 1000)
        }
      })
      return
    }
    let info = JSON.parse(user);
    console.log(info)
    this.setData({
      "personInfo": info
    })
  },
  init() {},
  //点击不同选择卡，执行不同操作
  onClickCell({
    currentTarget
  }) {
    const {
      dataset
    } = currentTarget;
    let info = this.data.personInfo
    console.log(currentTarget)
    switch (dataset.type) {
      case 'gender':
        this.setData({
          typeVisible: true,
        });
        break;
      case 'name':
        wx.navigateTo({
          url: `/pages/usercenter/name-edit/index?val=${info.username}&id=${info.userId}&type=0`,
        });
        break;
      case 'avatarUrl':
        this.toModifyAvatar();
        break;
      case 'phoneNumber':
        wx.navigateTo({
          url: `/pages/usercenter/name-edit/index?val=${info.mobile}&id=${info.userId}&type=1`,
        });
        break;
      case 'userType':
        this.setData({
          type2Visible: true,
        });
        break;
      case 'password':
        wx.navigateTo({
          url: `/pages/usercenter/pwd-edit/index?val=${info.username}&id=${info.userId}&type=0&mobile=${info.mobile}`,
        });
        break;
      default: {
        break;
      }
    }
  },
  changeInfo() {

    wx.showLoading({
      title: '修改中...',
    })
    wx.request({
      url: baseUrl + 'sys/user/wx/update',
      method: 'post',
      data: {
        userId: this.data.personInfo.userId,
        gender: this.data.personInfo.gender,
        type: this.data.personInfo.userType,
        avatarUrl: this.data.personInfo.avatarUrl
      },
      success: (res) => {
        wx.hideLoading()
        if (res.data.code === 0) {
          wx.setStorage({
            key: "userInfo",
            data: JSON.stringify(res.data.data)
          })
          wx.showToast({
            title: '修改成功',
            icon: 'success',
            duration: 1000,
            success() {
              setTimeout(function () {
                wx.navigateBack()
              }, 1000)
            }
          });
        } else {
          wx.showToast({
            title: res.data.msg,
            icon: 'error',
            duration: 2000
          });
        }
      }
    })
  },
  //关闭性别选择弹窗
  onClose() {
    this.setData({
      typeVisible: false,
    });
  },
  //关闭用户类型选择弹窗
  onClose2() {
    this.setData({
      type2Visible: false,
    });
  },
  getPhoneNumber(e) {
    console.log(e)
  },
  //性别设置
  onConfirm(e) {
    const {
      value
    } = e.detail;
    this.setData({
      typeVisible: false,
      'personInfo.gender': value,
    });

    this.changeInfo()
  },
  onConfirm2(e) {
    const {
      value
    } = e.detail;
    this.setData({
      type2Visible: false,
      'personInfo.userType': value,
    });

    this.changeInfo()
  },
  //返回按钮
  back() {
    wx.navigateBack({
      backRefresh: true
    });
  },
  //头像修改
  async toModifyAvatar() {
    try {
      let _this = this
      wx.chooseMedia({
        count: 1,
        mediaType: ['image'],
        sizeType: ['compressed'],
        sourceType: ['album', 'camera'],
        success: (res) => {
          const {
            path,
            size,
            tempFilePath
          } = res.tempFiles[0];
          if (size > 10485760) {
            wx.showToast({
              title: '图片大小超出限制，请重新上传',
              duration: 2000
            })
          }
          console.log(res)
          _this.onUpload(tempFilePath)

        },
        fail: (err) => reject(err),
      });

    } catch (error) {
      console.log(error)
      if (error.errMsg === '取消选择') return;
      Toast({
        context: this,
        selector: '#t-toast',
        message: error.errMsg || error.msg || '修改头像出错了',
        theme: 'error',
      });
    }
  },
  onUpload(file) {
    wx.showLoading({
      title: '加载中',
      mask: true
    })
    let _this = this
    wx.uploadFile({
      url: baseUrl + 'sys/file/addFile',
      filePath: file,
      name: 'file',
      success: (res) => {
        let resq = JSON.parse(res.data)
        wx.hideLoading()
        if (resq.code === 0) {
          _this.setData({
            'personInfo.avatarUrl': prefixUrl+resq.url,
          });
          wx.setStorageSync({
            key: "userInfo",
            data: JSON.stringify(res.data.data)
          })

    this.changeInfo()
          
        } else {
          wx.showToast({
            title: res.data.msg,
            icon: 'error',
            duration: 2000
          })
        }
      },
      fail(res) {
        wx.hideLoading()
        console.log(res)
      }
    });

  },

});